"""
日志 django中间件
"""
import json
from django.contrib.auth.models import AnonymousUser
from django.utils.deprecation import MiddlewareMixin
from common.models.system import OperationLog
from settings import conf
from utils.logger import acc_running_log
from utils.request_util import get_request_user, get_request_ip, get_request_data, get_request_path, get_os, \
    get_browser, get_verbose_name


class ApiLoggingMiddleware(MiddlewareMixin):
    """
    用于记录API访问日志中间件
    """

    def __init__(self, get_response=None):
        super().__init__(get_response)
        #self.enable = getattr(conf, 'API_LOG_ENABLE', None) or False
        self.enable = True
        self.methods = getattr(conf, 'API_LOG_METHODS', None) or set()
        self.request_modular = ''
        self.operation_log_id = None

    @classmethod
    def __handle_request(cls, request):
        request.request_ip = get_request_ip(request)
        request.request_data = get_request_data(request)
        request.request_path = get_request_path(request)

    def __handle_response(self, request, response):
        # request_data,request_ip由PermissionInterfaceMiddleware中间件中添加的属性
        body = getattr(request, 'request_data', {})
        _api_name = request.GET.get('_api_name', '')
        # 目前仅记录添加为按钮的  操作记录
        if not _api_name:
            return
        # 请求含有password则用*替换掉(暂时先用于所有接口的password请求参数)
        if isinstance(body, dict) and body.get('password', ''):
            body['password'] = '*' * len(body['password'])
        if not hasattr(response, 'data') or not isinstance(response.data, dict):
            response.data = {}
        try:
            if not response.data and response.content:
                content = json.loads(response.content.decode())
                response.data = content if isinstance(content, dict) else {}
        except Exception:
            return
        user = get_request_user(request)
        info = {
            'request_modular': self.request_modular,
            'request_ip': getattr(request, 'request_ip', 'unknown'),
            'creator': user if not isinstance(user, AnonymousUser) else None,
            'request_method': request.method,
            'request_path': request.request_path,
            'request_body': body,
            'request_api_name': _api_name,
            'response_code': response.data.get('code'),
            'request_os': get_os(request),
            'request_browser': get_browser(request),
            'request_msg': request.session.get('request_msg'),
            'status': True if response.data.get('code') in [2000, ] else False,
            'json_result': {'code': response.data.get('code'), 'msg': response.data.get('msg')},
        }
        OperationLog.objects.create(**info)
        # operation_log, creat = OperationLog.objects.update_or_create(defaults=info, id=self.operation_log_id)
        # if not operation_log.request_modular and conf.API_MODEL_MAP.get(request.request_path, None):
        #     operation_log.request_modular = conf.API_MODEL_MAP[request.request_path]
        #     operation_log.save()

    def process_view(self, request, view_func, view_args, view_kwargs):
        if hasattr(view_func, 'cls') and hasattr(view_func.cls, 'queryset'):
            if not self.enable:
                return
            if self.methods == 'ALL' or request.method in self.methods:
                # log = OperationLog(request_modular=get_verbose_name(view_func.cls.queryset))
                # log.save()
                # self.operation_log_id = log.id
                self.request_modular = get_verbose_name(view_func.cls.queryset)
                if not self.request_modular and conf.API_MODEL_MAP.get(request.request_path, None):
                    self.request_modular = conf.API_MODEL_MAP[request.request_path]
        return

    def process_request(self, request):
        self.__handle_request(request)

    def process_response(self, request, response):
        """
        主要请求处理完之后记录
        :param request:
        :param response:
        :return:
        """
        if self.enable:
            if self.methods == 'ALL' or request.method in self.methods:
                self.__handle_response(request, response)
        return response


class AccApiLoggingMiddleware(MiddlewareMixin):
    """
    用于记录acc API访问日志中间件
    """

    def __init__(self, get_response=None):
        super().__init__(get_response)
        self.enable = getattr(conf, 'API_LOG_ENABLE', None) or False
        self.methods = getattr(conf, 'API_LOG_METHODS', None) or set()

    @classmethod
    def __handle_request(cls, request):
        request.request_ip = get_request_ip(request)
        request.request_data = get_request_data(request)
        request.request_path = get_request_path(request)

    def __handle_response(self, request, response):
        # request_data,request_ip由PermissionInterfaceMiddleware中间件中添加的属性
        body = getattr(request, 'request_data', {})
        # 请求含有password则用*替换掉(暂时先用于所有接口的password请求参数)
        if isinstance(body, dict) and body.get('password', ''):
            body['password'] = '*' * len(body['password'])
        if not hasattr(response, 'data') or not isinstance(response.data, dict):
            response.data = {}
        if body.get('base64_file'):
            del body['base64_file']
        try:
            if not response.data and response.content:
                content = json.loads(response.content.decode())
                response.data = content if isinstance(content, dict) else {}
        except Exception:
            return

        user = get_request_user(request)
        acc_running_log.info('[%s] [%s] [%s] with parameters [user_id=%s] [request=%s] [response=%s]'
                             % (request.headers.get('X-Forwarded-For'), request.method, request.path, user.id,
                                body, {'code': response.data.get('code'), 'msg': response.data.get('msg')}))

    def process_request(self, request):
        self.__handle_request(request)

    def process_response(self, request, response):
        """
        主要请求处理完之后记录
        :param request:
        :param response:
        :return:
        """
        if self.enable:
            if self.methods == 'ALL' or request.method in self.methods:
                self.__handle_response(request, response)
        return response
